﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Reflection;


namespace Kernelx.Contexts.AspNetCoreImpls
{ 
    using Core;
    using Defaults;

    internal class HttpRequestParameterCollection : RequestParameterCollectionBase
    {
        public HttpRequestParameterCollection(HttpRequest httpRequest) : base(() => GetData(httpRequest)) { }

        static IDictionary<string, object> GetData(HttpRequest request)
        {
            var data = new Dictionary<string, object>();
            if (request != null)
            {
                //从query中读取
                foreach (var q in request.Query)
                    data[q.Key] = q.Value.Count > 1 ? q.Value.ToArray() : q.Value.ToString();

                //从form表单中读取
                if (request.HasFormContentType)
                {
                    foreach (var f in request.Form)
                        data[f.Key] = f.Value.Count > 1 ? f.Value.ToArray() : f.Value.ToString();
                }

                //从mvc的httpRequest的RouteValues中读取
                var rvp = request.GetType().GetProperty("RouteValues", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                if (rvp != null)
                {
                    var specialKeys = new string[] { "area", "controller", "action" };
                    var routevalues = rvp.GetValue(request);
                    var kp = routevalues.GetType().GetProperty("Keys");
                    var vp = routevalues.GetType().GetProperty("Values");
                    var keys = (kp.GetValue(routevalues) as IEnumerable<string>).ToList();
                    var values = (vp.GetValue(routevalues) as IEnumerable<object>).ToList();
                    for (var i = 0; i < keys.Count; i++)
                    {
                        var key = keys[i];
                        if (specialKeys.Contains(key))
                            continue;
                        data[key] = values[i];
                    }
                }

                //从body请求体中读取
                if (request.Body.CanRead && (request.ContentType ?? string.Empty).Contains("json"))
                {
                    request.Body.Seek(0, SeekOrigin.Begin);
                    var reader = new StreamReader(request.Body);
                    var content = reader.ReadToEndAsync().Result;
                    if (!string.IsNullOrEmpty(content))
                    {
                        var serializer = WorkloadStartupContext.Current.GetJsonSerializer();
                        var temp = serializer.DeserializeObject<Dictionary<string, object>>(content);
                        foreach (var kv in temp)
                            data[kv.Key] = kv.Value?.ToString();
                    }
                }
            }

            return data;
        }

    }
}
